// 更新用户手机等信息
var basePage = require('../../../common/BasePage');
var area = require('../../../utils/area');
var util = require('../../../utils/util');
Page({
	behaviors: [basePage],
	/**
	 * 页面的初始数据
	 */
	data: {
        checkMobile: false,
        region:[],
		areaList: area.areaList,
		/**显示区域选择 */
		showArea: false,
		/**姓名 */
		name: '',
		/**手机号 */
		mobile: '',
		/**区域 */
		area: '',
		/**地址 */
		addr: '',
		house: "",
		lat: "",
		lng: "",
		/* 是否完善资料 */
		mobile_bind: "",
		/**请求参数 */
		reqData: {
			province_code: '',
			city_code: '',
			district_code: '',
			province: '',
			city: '',
			district: '',
		},
		avatarUrl: '/assets/common/logo.png',
		updataUrl:"",
		type: 1, //1完善资料2完善头像昵称
		nick: "",
		location:"",//定位
		selectArticle:false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
        console.log("ar", this.data.areaList);
        this.getAreas()
		this.setData({
			type: options.type
		})
		if(options.type==2){
			console.log("userInfo",getApp().globalData.userInfo)
			this.setData({
				avatarUrl:getApp().globalData.userInfo.thumb,
				updataUrl:getApp().globalData.userInfo.face,
				nick:getApp().globalData.userInfo.nickname
			})
		}

		// this.data.areaList=area.areaList
    },
    getAreas() {
        let that = this
        wx.request({
            url: that.data.host+"/uploads/gaode.json",
            header: {},
            success(res) {
                let result = res.data.districts[0].districts
                let arrs = [{
                    values: result
                }, {
                    values: result[0].districts,
                    defaultIndex: 0,
                }, {
                    values: result[0].districts[0].districts,
                    defaultIndex: 0,
                }]
                that.setData({
                    addrs: arrs
                })
            }
        })
    },
    // 省市区变动
    onAreaChange(e) {
        const {
            picker,
            value,
            index
        } = e.detail;
        if (index === 0) {
            // 修改省
            picker.setColumnValues(1, value[0].districts);
            picker.setColumnValues(2, value[0].districts[0].districts);
        } else if (index === 1) {
            // 修改市
            picker.setColumnValues(2, value[1].districts);
        }
    },
    // 确认选择省市区
    onAreaConfirm(e) {
        let areaArr = e.detail.value;
        let reqData = this.data.reqData;
        //初始化省市县数据
        reqData.province = areaArr[0].name;
        reqData.province_code = areaArr[0].adcode;
        reqData.city = areaArr[1].name;
        reqData.city_code = areaArr[1].adcode;
        reqData.district = areaArr[2].name;
        reqData.district_code = areaArr[2].adcode;
        this.setData({
            area: reqData.province + reqData.city + reqData.district,
            showArea: false,

        })
    },
	/**选择好区域 */
	area_ok(e) {
		console.log("area_ok", e);
		let areaArr = e.detail.values;
		let reqData = this.data.reqData;
		//初始化省市县数据
		reqData.province = areaArr[0].name;
		reqData.province_code = areaArr[0].code;
		reqData.city = areaArr[1].name;
		reqData.city_code = areaArr[1].code;
		reqData.district = areaArr[2].name;
		reqData.district_code = areaArr[2].code;
		this.setData({
			area: reqData.province + reqData.city + reqData.district,
			showArea: false
		})
    },
    bindRegionChange: function (e) {
        console.log('picker发送选择改变，携带值为', e)


        let areaArr = e.detail.value;
        let codeArr = e.detail.code;
        let reqData = this.data.reqData;
        //初始化省市县数据
        reqData.province = areaArr[0];
        reqData.province_code = codeArr[0];
        reqData.city = areaArr[1];
        reqData.city_code = codeArr[1];
        reqData.district = areaArr[2];
        reqData.district_code = codeArr[2];
        this.setData({
            area: reqData.province + reqData.city + reqData.district,
            showArea: false,
            region: e.detail.value

        })
    },
	submit_click() {
		if(!this.data.selectArticle){
			wx.showToast({
				title: '请阅读并同意用户协议和隐私政策',
				icon:"none"
			})
			return
        }
        
		if(this.data.type==1){//完善手机号等
			let reqData = this.data.reqData;
			let errorTip = '';
			!this.data.name ? errorTip += '请填写姓名' + '\n\r' : reqData.name = this.data.name;
			!this.data.mobile ? errorTip += '请填写手机号' + '\n\r' : reqData.mobile = this.data.mobile;
			!this.data.area ? errorTip += '请选择区域' + '\n\r' : '';
			!this.data.house ? errorTip += '请填写详细地址' + '\n\r' : "";
			
			
			reqData.house = this.data.house
			reqData.addr = this.data.area

			reqData.lng = this.data.lng
			reqData.lat = this.data.lat
			reqData.location=this.data.location
			// reqData.contact=this.data.name
			// if (this.data.mobile_bind != 1) {
			// 	// !this.data.area ? errorTip += '请选择区域' + '\n\r' : '';
			// 	// !this.data.addr ? errorTip += '请选择详细地址' + '\n\r' : "";
			// 	reqData.addr = this.data.area+this.data.house
			// }
	
			if (errorTip) {
				return wx.showModal({
					content: errorTip,
					showCancel: false,
					title: '提示',
				})
            }
            reqData.name= util.replaceStr(reqData.name)
            reqData.mobile= util.replaceStr(reqData.mobile)
            reqData.house= util.replaceStr(reqData.house)
            console.log("完善资料提交", reqData)
			this.request({
				loadingTip: '加密提交中',
				url: this.data.host + '/home/user/updateMobile',
				method: "POST",
				data: reqData
			}, res => {
				getApp().globalData.userInfo.mobile_bind = 1;
				this.getuserInfo()
				wx.showToast({
					title: '提交成功',
					icon: 'success'
				})
				wx.navigateBack({
					delta: 1,
				})
			});
		}else if(this.data.type==2){//完善头像昵称
			var param={
				face:this.data.updataUrl,
				nickname:this.data.nick
            }
            param.nickname= util.replaceStr(param.nickname)
			console.log("头像昵称",param)
			this.request({
				url: this.data.host + '/home/user/audit',
				data: param,
				method: "POST",
			}, () => {
				getApp().globalData.userInfo.thumb = this.data.avatarUrl;
				getApp().globalData.userInfo.nickname = this.data.nick;
				this.getuserInfo()
				wx.showToast({
					title: '提交成功',
					icon: 'success'
				})
				wx.navigateBack({
					delta: 1,
				})
			})
		}
		


	},

	getuserInfo() {
		this.request({
			url: this.data.host + "/home/user/info"
		}, res => {
			
		});
	},

	/**打开地图 */
	// open_map_click(event) {
	// 	let that = this;
	// 	wx.authorize({
	// 		scope: 'scope.userLocation',
	// 		success() {
	// 			wx.chooseLocation({
	// 				success: res => {
	// 					console.log("chooseLocation", res);
	// 					that.setData({
	// 						addr: res.address,
	// 						house: res.name,
	// 						lat: res.latitude,
	// 						lng: res.longitude
	// 					})
	// 				},
	// 				fail: e => {
	// 					console.log(e);
	// 					wx.showToast({
	// 						title: e.errMsg || '获取微信位置失败：',
	// 						icon: 'none'
	// 					})
	// 				}
	// 			})
	// 		},
	// 		fail(e) {
	// 			that.setData({
	// 				openSetting: true
	// 			});
	// 			console.log('授权位置失败', e);
	// 		}
	// 	})


	// },
	toAdress() {
		wx.navigateTo({
			url: '/pages/addr/AddrList',
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		console.log("onShow",this.data.userInfo);
		if (this.data.userInfo.name) {
			let reqData = this.data.reqData;
			// //初始化省市县数据
			reqData.province = this.data.userInfo.province
			reqData.province_code = this.data.userInfo.province_code
			reqData.city = this.data.userInfo.city
			reqData.city_code = this.data.userInfo.city_code
			reqData.district = this.data.userInfo.district
			reqData.district_code = this.data.userInfo.district_code
			this.setData({
				name: this.data.userInfo.name,
				mobile: this.data.userInfo.mobile,
				mobile_bind: this.data.userInfo.mobile_bind,
				area: this.data.userInfo.addr,
				house: this.data.userInfo.house,
				lng:this.data.userInfo.lng,
				lat:this.data.userInfo.lat,
				location:this.data.userInfo.location,
				reqData: reqData
			})
		}
	},
	onChooseAvatar(e) {
		console.log("选择头像", e)
		let that = this;
		const { avatarUrl } = e.detail;
		wx.uploadFile({
			filePath: avatarUrl,
			name: 'image',
			url: that.data.host + '/home/upload/image',
			formData: {
				from: 'face'
			},
			success(res) {
				
				if (res.statusCode != 200) {
					return wx.showModal({
						showCancel: false,
						content: res.errMsg || '上传失败',
					})
				}else{
					let resObj = JSON.parse(res.data);
					var url=that.get_thumb(resObj.data.path)
					console.log("头像",url)
					that.setData({
						avatarUrl:url,
						updataUrl:resObj.data.path
					})
				}
				

			},
			fail() {
				wx.showModal({
					showCancel: false,
					content: '上传接口异常',
				})
			},
			complete() {
				
			}
		});
	},
	onArea(){
    var that= this
    wx.chooseLocation({
      success(res){
        console.log("选择地址",res)
        that.setData({
          lat:res.latitude,
          lng:res.longitude,
          location:res.name
        })
      },
      fail(err){
        console.log("错误",err)
      }
    })
	},
	
	onArticle() {
		this.setData({
				selectArticle: !this.data.selectArticle
		})
	},
	//跳转源花买家协议
	toArticle(e) {
		var article_id=e.currentTarget.dataset.id
		wx.navigateTo({
				url: '/pages/article/Index?article_id=' + article_id,
		})
},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {


	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})